<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/27
 * Time: 18:10
 */
namespace app\appmsg\controller;

use app\common\helper\appmsg_helper;
use app\common\helper\emotion_helper;
use app\common\model\Appmenu;
use app\common\model\Appmsg;
use think\facade\View;
use think\facade\Config;
use think\facade\Request;
use think\facade\Filesystem;
use app\admin\controller\AdminBase;

class Save extends AdminBase
{

    public function __call($action = '', $params = array())
    {
        $action = (int)$action;
        if (!in_array($action, array(1, 2))) {
            return '提交地址不存在';
        }

        if ($action == 1) {
            return $this->single_save();
        } else {
            return $this->multi_save();
        }
    }

    // 保存单图文
    private function single_save()
    {
        $id            = Request::post('id', 0);
        $title         = trim(Request::post('title'));
        $cover         = trim(Request::post('cover'));
        $intro         = trim(Request::post('intro'));
        $content_type  = Request::post('content_type', 1);
        $link          = trim(Request::post('link'));
        $content       = Request::post('content');
        $show_cover    = trim(Request::post('show_cover'));
        $source_url    = trim(Request::post('source_url'));

        //exit($cover);
        if (!$title) {
            return ['info' => '信息标题不能为空'];
        }

        if ($content_type == 1) {
            if (!$link) {
                return ['info' => '图文链接不能为空'];
            }

            if ($this->store_id >= 1) {
                return ['info' => '店铺不允许发送纯链接图文，请修改'];
            }

            $link = check_http_start($link);
        } else {
            if (!$content) {
                return ['info' =>'图文详情不能为空'];
            }

            // 是否有外链图片
            $flag = has_out_link($content);
            if ($flag) {
                return ['info' => '当前图文中存在外链图片或.bmp图片，将不能用于推送，请修改'];
            }
        }

        // 店铺添加或修改的图文，初始状态为待审
        $verify = 1;
//        if ($this->store_id) {
//            $verify = 4;
//        }

        $store_id = $this->store_id;

        $appmsg_info = array();
        if ($id) {
            $appmsg_info = _uri('appmsg', ['id' => $id]);
            if (!$appmsg_info) {
                return ['info' => '该图文信息不存在'];
            }

            $verify = $appmsg_info['verify'];
            // 这个处理，防止总后台帮店铺编辑时覆盖了店铺id
            $store_id = $appmsg_info['store_id'];
        }


        $info = array(
            'company_id'   => $this->company_id,
            'open_card_id' => $this->open_card_id,
            'store_id'     => $store_id,
            'title'        => $title,
            'intro'        => $intro,
            'link'         => $link,
            //'content'      => AnString::html_purifier($content),
            'content'      => emotion_helper::emoji_to_code($content),
            //'content'      => str_replace('&wx_lazy=1', '', $content),
            //'content'      => str_replace('from=5&', 'from=5', $content),
            'content_type' => $content_type,
            'type'         => 1,
            'show_cover'   => $show_cover,
            'source_url'   => $source_url,
            'verify'       => $verify
        );

        if ($cover) {
            $info['cover'] = $cover;
        }

        // cover_is_change=1 是为同步永久素材时是否重新上传封面的依据
        if ($appmsg_info && $appmsg_info['cover'] != $cover) {
            $info['cover_is_change'] = 1;
        }

        if ($id) {
            // 没有id时，verify走默认状态
            //unset($info['verify']);

            Appmsg::update($info, ['id'=>$id]);

        } else {
            $appmsg = Appmsg::create($info);
            $id = $appmsg->id;
        }

        return array('info'=>'ok', 'id'=>$id, 'verify'=>$verify);
    }

    // 保存多图文
    private function multi_save()
    {
        $data = Request::post('data',array());
        // 店铺添加或修改的图文，初始状态为待审
        $verify = 1;
//        if ($this->store_id) {
//            $verify = 4;
//        }

        $ids = array();
        $main_id = 0;
        if (isset($data[0]['id']) && $data[0]['id']) {
            $mainmsg_info = _uri('appmsg', ['id' => $data[0]['id']]);
            if (!$mainmsg_info) {
                return ['info' => '该图文信息不存在'];
            }

            $verify = $mainmsg_info['verify'];

            $main_id = $mainmsg_info['id'];

            $ids = getFields('appmsg','id', array('merge_id'=>$main_id),['view_order', 'asc']);
            array_unshift($ids, $main_id);
        }

        // 提交前的验证，不能传外链图文和纯链接图文
        foreach ($data as $k=>$v) {
            if (!isset($v['content_type'])) {
                return ['info' => '图文类型不对，请选择链接图文或内容图文'];
            }

            if ($v['content_type'] == 1) {
//                if ($this->store_id >= 1) {
//                    return ['info' => '店铺不允许发送纯链接图文，请修改'];
//                }

            } else {
                if (!$v['content']) {
                    return ['info' => '图文详情不能为空'];
                }

                // 是否有外链图片
                $flag = has_out_link($v['content']);
                if ($flag) {
                    return ['info' => '当前图文中存在外链图片，将不能用于推送，请修改'];
                }
            }
        }

        $new_ids = array();
        foreach ($data as $k=>$v) {
            if (!$v['title']) {
                continue;
            }
            if (isset($v['link']) && trim($v['link'])) {
                $v['link'] = check_http_start($v['link']);
            }

            // 如果是关联图文，只存关联id、view_order、merge_id
            if (isset($v['relation_id']) && (int)$v['relation_id'] > 0) {
                $v = array(
                    'id'          => isset($v['id']) ? $v['id'] : 0,
                    'relation_id' => $v['relation_id']
                );
            }

            // 如果是取消关联
            if (isset($v['cancel_relation'])) {
                if ((int)$v['cancel_relation'] == 1) {
                    $v['relation_id'] = 0;
                }

                unset($v['cancel_relation']);
            }

            $v['type']       = 2;
            $v['view_order'] = $k;
            if ($k > 0) {
                $v['merge_id'] = $main_id;

            } else {
                // 没有id时，verify走默认状态
                if (!isset($v['id']) || !$v['id']) {
                    //$v['verify'] = $verify;
                }
                $v['verify'] = $verify;
            }

            if (isset($v['real_cover'])) {
                unset($v['real_cover']);
            }

            if (isset($v['content']) && $v['content']) {
                //$v['content'] = str_replace('&wx_lazy=1', '', $v['content']);
                //$v['content'] = str_replace('from=5amp', 'from=5', $v['content']);
            }

            // 这个处理，1：要给图文加上store_id，2：防止总后台帮店铺编辑时覆盖了店铺id
            if ($this->store_id && (!isset($v['store_id']) || !$v['store_id'])) {
                $v['store_id'] = $this->store_id;
            }

            $pre_appmsg_info = array();
            if (isset($v['id'])  && $v['id']) {
                $pre_appmsg_info = _uri('appmsg',['id'=>$v['id']]);
            }

            // cover_is_change=1 是为同步永久素材时是否重新上传封面的依据
            if (isset($v['cover']) && $v['cover']) {
                if ($pre_appmsg_info && $pre_appmsg_info['cover'] != $v['cover']) {
                    $v['cover_is_change'] = 1;
                }
            }

            // 如果存在，则更新
            if (isset($v['id']) && in_array($v['id'], $ids)) {
                // 编辑时没有上传图片排除
                if (isset($v['cover']) && !$v['cover']) {
                    unset($v['cover']);
                }

                Appmsg::update($v, ['id'=>$v['id']]);

                $tmp_id = $v['id'];

                // 不存在，则添加
            } else {
                $v['company_id']   = $this->company_id;
                $v['open_card_id'] = $this->open_card_id;
                $msg = Appmsg::create($v);
                $tmp_id = $msg->id;
            }

            if ($k == 0 && !$main_id) {
                $main_id = $tmp_id;
            }

            $new_ids[] = $tmp_id;
        }

        foreach (array_diff($ids, $new_ids) as $v) {
            Appmsg::where(['id'=>$v])->delete();
        }

        return array('info'=>'ok', 'id'=>$main_id, 'ids'=>$new_ids, 'verify'=>$verify);
    }

    /**
     * 用隐藏iframe上传图片
     */
    public function upload_file()
    {
        $type        = Request::param('type', 1);
        $file_field  = 'upload_cover';
        $allow_type  = Config::get('allow_image_type');
        $upload_path = UPLOAD_PATH;
        $failed_msg  = check_upload($_FILES[$file_field]);

        //var_dump($failed_msg);
        //exit;

        $file = request()->file($file_field);

        if (empty($failed_msg)) {
            // 上传
            //$uploadr = new \Uploadr($upload_path, $allow_type);
            $file = request()->file($file_field);
            try {
                //$file_path = $uploadr->uploadFile($_FILES[$file_field]['tmp_name']);
                $file_path = Filesystem::disk('public')->putFile(config('admin.upload_dir'), $file);
            } catch (\Exception $e) {
                $failed_msg = $e->getMessage();
            }
            if (!empty($file_path)) {
                $image_size = get_image_info(ROOT_PATH.'/public/storage/'.$file_path);
                if ($type == 1) {
                    make_thumb($file_path, 'appmsg', 1);
                } else {
                    make_thumb($file_path, 'appmsg', 2);
                }
                make_thumb($file_path, 'appmsg', 3);


                $small_img = _image($file_path, 'big');
                $small_img = str_replace('/static/upload', '', $small_img);

                $file_path = str_replace('\\', '/', $file_path);
                //dump($small_img, $file_path);exit;
                echo '<script>';
                echo 'window.parent.upfileFinish("'.SITE_URL.$small_img.'", "'.$file_path.'");';
                echo '</script>';
            }
        }

        if ($failed_msg) {
            echo '<script>';
            echo 'window.parent.upfileFinish("", "", "'.$failed_msg.'");';
            echo '</script>';
        }
    }
}